import React, {Component} from 'react';
import moment from 'moment';
import {
	AppRegistry,
	Dimensions,
	Platform,
	NativeModules,
	DeviceInfo,
	StyleSheet,
	Image,
	Text,
	View,
	TextInput,
	PixelRatio,
	TouchableOpacity,
	FlatList,
	ActivityIndicator,
	DeviceEventEmitter
} from 'react-native';

var Common = require('./common');
var num = 4;//分页
// iPhoneX
const X_WIDTH = 375;
const X_HEIGHT = 812;

// screen
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

const pixelRatio = PixelRatio.get();
const dismissKeyboard = require('dismissKeyboard');
export default class MineHudongPage extends Component {
	// 此处设置 Tab 的名称和一些样式，这里的会覆盖掉配置路由文件的样式，下面会讲
	static navigationOptions = {
		tabBarLabel: '资讯',
		tabBarIcon: ({focused}) => {
			if (focused) {
				return (
					<Image style={[styles.bnavImg, {width: 22, height: 22}]} source={require('./images/zixun1.png')}/>
				);
			}
			return (
				<Image style={[styles.bnavImg, {width: 22, height: 22}]} source={require('./images/zixun.png')}/>
			);
		},
	};

	constructor(props) {
		super(props);
		this.state = {
			iphonex: false,
			showCeng: false,
			str: '推荐',
			news: [],
			imgsrc: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1514356844477&di=7c57fde0860194258cbec5c2720e0cf5&imgtype=0&src=http%3A%2F%2Fwww.swkweike.com%2Fdata%2Fuploads%2F2015%2F05%2F26%2F20430804665564348adc669.png',
			loadId: null,
			refreshing: false,//下拉刷新
			hasMore: true,//是否有更多数据
			endText: '加载更多...',
			orderby: 'recommend',
			diggArr: {},
			collectArr: {},
			type: 'all'
		};
	}

	isIphoneX() {

		return (

			Platform.OS === 'ios' &&

			((SCREEN_HEIGHT === X_HEIGHT && SCREEN_WIDTH === X_WIDTH) ||

				(SCREEN_HEIGHT === X_WIDTH && SCREEN_WIDTH === X_HEIGHT))

		)

	}


	ifIphoneX() {
		var flag = this.isIphoneX();
		if (flag) {
			console.log('true')
			this.setState({
				iphonex: true
			})
		} else {
			console.log('false')
			this.setState({
				iphonex: false
			})
		}
	}


	login() {
		var _this = this;
		Common.ajaxPost(Common.url + 'login.php', function (res) {
			if (res.code == "0000") {

			}
		}.bind(this), {verify: '08login', t: ''});
	}

	toRegister() {
		this.props.navigation.navigate('Register')
	}

  toSearch() {
		this.props.navigation.navigate('Search')
	}

	toHome() {

		this.props.navigation.navigate('Home')
	}

	//跳到资讯列表
	toNewsList() {
		this.props.navigation.navigate('NewsList', {from: 'home'})
	}

	toMine() {
		this.props.navigation.navigate('Mine')
	}

	changeTabs(str) {
		this.setState({
			str: str
		})
		num = 1;
		if (str == '推荐') {
			this.setState({
				orderby: 'recommend',
				news: []
			}, () => {
				this.getData();
			})
		}
		else if (str == '最新') {
			this.setState({
				orderby: 'new',
				news: []
			}, () => {
				this.getData();
			})
		}
		else {
			this.setState({
				orderby: 'hot',
				news: []
			}, () => {
				this.getData();
			})
		}
	}

	renderPic(pic) {
		return pic.map(function (data, index) {
			return (
				<Image style={styles.imgsItem} source={{uri: data.attach_url}}/>
			);
		})
	}

	renderNews(data) {
		var _this = this;
		var bgColor = '#fff';
		if (data != undefined) {
			return (
				<TouchableOpacity style={styles.newsItem} onPress={_this.toDetail.bind(_this, data.item)}>
					<View style={styles.user}>
						<Image style={{width: 36, height: 36, borderRadius: 18}}
						       source={{uri: data.item.user_info.avatar_original}}/>
						<View style={{paddingLeft: 10,}}>
							<Text style={styles.userText}>{data.item.user_info.uname}</Text>
							<Text style={{fontSize: 14, color: '#8c8c8c'}}>{data.item.publish_time}</Text>
						</View>
					</View>
					<Text style={styles.newsTitle}>{data.item.content_txt}</Text>
					<View style={styles.imgs}>
						{data.item.var && data.item.var.attachInfo && data.item.var.attachInfo.length ? (
							_this.renderPic(data.item.var.attachInfo)
						) : (null)}
					</View>
					<View style={styles.hudong}>
						<TouchableOpacity style={styles.hodongItem}>
							<Image style={{width: 22, height: 22, marginRight: 6}}
							       source={require('./images/shoucang.png')}/>
							<Text>{data.item.collect_count}</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.hodongItem}>
							<Image style={{width: 22, height: 22, marginRight: 6}}
							       source={require('./images/zan.png')}/>
							<Text>{data.item.digg_count}</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.hodongItem}>
							<Image style={{width: 22, height: 22, marginRight: 6}}
							       source={require('./images/pinglun.png')}/>
							<Text>{data.item.comment_count}</Text>
						</TouchableOpacity>
					</View>
				</TouchableOpacity>
			);
		} else {
			return (
				<Text>空</Text>
			)
		}

	}

	keyExtractor = (item, index) => item.feed_id;//生成key
	refresh() {
		num = 4;
		this.setState({
			refreshing: true
		})
		this.getData();
	}

	loadMore() {
		console.log('loadMore');
		num++;

		console.log('hasMore', this.state.hasMore);
		if (this.state.hasMore) {
			this.getData();
		}
		else {
			this.setState({
				endText: '无更多数据'
			})
		}
	}

	renderFooter() {
		console.log('renderFooter');
		if (this.state.refreshing) {
			return (
				<View style={{padding: 20}}>
					<ActivityIndicator/>
					<Text style={{textAlign: 'center'}}>{this.state.endText}</Text>
				</View>
			)
		}
		else {
			return (
				<View></View>
			)
		}
	}

	getData() {
		var _this = this;

		Common.ajaxGet(Common.url + 'thinksns/index.php?app=widget&mod=FeedList&act=loadMore&loadId=' + this.state.loadId + '&type=' + this.state.type + '&feed_type=&feed_key=&fgid=&topic_id=&load_count=' + num + '&is_ajax=1&orderby=' + this.state.orderby, function (res) {
			console.log(res)
			if (res.status == 1) {
				var data = res.list;
				if (data.data && data.data.length) {
					this.setState({
						diggArr: data.diggArr,
						collectArr: data.collectArr
					})
					for (var item of data.data) {
						item.publish_time = moment(parseFloat(item.publish_time + '000')).format('YYYY-MM-DD HH:mm:ss');
						if (!item.collect_count) {
							item.collect_count = 0;
						}
						if (!item.digg_count) {
							item.digg_count = 0;
						}
						if (!item.comment_count) {
							item.comment_count = 0;
						}
					}
					this.setState({
						loadId: data.data[data.data.length - 1].feed_id,
						news: this.state.news.concat(data.data),
						refreshing: false,
						hasMore: true,
					})

				} else {
					this.setState({
						hasMore: false,
						refreshing: false,
					})
					console.log('hasMore', this.state.hasMore);
				}
			}
		}.bind(this), {verify: '08login', t: ''});
	}

	toDetail(item) {
		var json = item;
		json.collectArr = this.state.collectArr;
		json.diggArr = this.state.diggArr;
		this.props.navigation.navigate('HudongDetail', json)
	}

	toSendWords() {
		this.props.navigation.navigate('SendWords');
		this.hideCeng();
	}

	toSendVideo() {
		this.props.navigation.navigate('SendVideo');
		this.hideCeng();
	}

	showCeng() {
		this.setState({
			showCeng: true,
		})
	}

	hideCeng() {
		this.setState({
			showCeng: false,
		})
	}

	componentWillMount() {
		if (this.props.navigation.state.params) {
			this.setState({
				type: this.props.navigation.state.params
			})
		}

		this.ifIphoneX();
		// console.log(this.props.navigation.state.params)
		// if(this.props.navigation.state.params.from){
		//   this.setState({
		//     from:this.props.navigation.state.params,
		//   })
		// }
	}

	componentDidMount() {
		num = 4;
		this.getData();
		this.listener = DeviceEventEmitter.addListener('reloadHudong', (value) => {
			this.setState({
				news: []
			}, () => {
				this.getData();
			})

		});

		// console.log(this.props.navigation.state.params)
		// if(this.props.navigation.state.params.from){
		//   this.setState({
		//     from:this.props.navigation.state.params,
		//   })
		// }
	}

	componentWillUnmount() {
		//页面离开发送通知

		this.listener.remove();
	}

	render() {
		return (
			<View style={styles.container}>
				<View style={styles.logo}>
					<TouchableOpacity style={styles.fakeInput} activeOpacity={1} onPress={this.toSearch.bind(this)}>
						<Image style={{width: 15, height: 15, marginRight: 10, marginLeft: 10}}
						       source={require('./images/sousuo.png')}/>
						<Text style={{color: '#fff'}}>奥迪</Text>
					</TouchableOpacity>
				</View>


				{this.state.news.length ? (
					<FlatList
						ListFooterComponent={this.renderFooter.bind(this)}
						renderItem={this.renderNews.bind(this)}
						data={this.state.news}
						onEndReachedThreshold={0.2}
						onEndReached={this.loadMore.bind(this)}
						onRefresh={this.refresh.bind(this)}
						refreshing={this.state.refreshing}
						keyExtractor={this.keyExtractor.bind(this)}
						style={{height: Common.screenHeight - 150}}
					/>
				) : (
					<View
						style={{alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff', marginTop: 5}}>
						<Text style={[{
							padding: 20,
							width: Common.screenWidth,
							textAlign: 'center',
							fontSize: 16,
							color: '#333'
						}]}>无数据</Text>
					</View>
				)}


				<TouchableOpacity style={styles.addImg} onPress={this.showCeng.bind(this)}>
					<Image style={styles.fabuanniu} source={require('./images/fabuanniu.png')}/>
				</TouchableOpacity>
				{this.state.showCeng ? (
					<View style={styles.ceng}>
						<View
							style={[styles.black, {height: this.state.iphonex ? Common.screenHeight - 175 : Common.screenHeight - 175}]}></View>
						<View style={styles.forbtn}>
							<View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}>
								<TouchableOpacity style={{
									flex: 1,
									flexDirection: 'column',
									alignItems: 'center',
									justifyContent: 'center'
								}}
								                  onPress={this.toSendWords.bind(this)}
								>
									<Image style={{width: 62, height: 62,}} source={require('./images/fabutuwen.png')}/>
									<Text style={{paddingTop: 15, fontSize: 16}}>图文</Text>
								</TouchableOpacity>
								<TouchableOpacity style={{
									flex: 1,
									flexDirection: 'column',
									alignItems: 'center',
									justifyContent: 'center'
								}}
								                  onPress={this.toSendVideo.bind(this)}
								>
									<Image style={{width: 62, height: 62,}}
									       source={require('./images/fabushipin.png')}/>
									<Text style={{paddingTop: 15, fontSize: 16}}>视频</Text>
								</TouchableOpacity>
								<TouchableOpacity style={[styles.close, {bottom: this.state.iphonex ? -30 : 10}]}
								                  onPress={this.hideCeng.bind(this)}>
									<Image style={{width: 22, height: 22,}}
									       source={require('./images/fatieguanbi.png')}/>
								</TouchableOpacity>
							</View>
						</View>
					</View>
				) : (null)}

			</View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		height: Common.screenHeight,
		backgroundColor: '#fff',
	},
	logo: {
		height: 45,
		width: Common.screenWidth,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: '#3c78ff'
	},
	fakeInput: {
		width: Common.screenWidth * 0.7,
		height: 25,
		backgroundColor: '#86abfd',
		borderRadius: 12,
		flexDirection: 'row',
		alignItems: 'center',
	},
	tabs: {
		flexDirection: 'row',
		alignItems: 'flex-end',
		justifyContent: 'center',
		paddingTop: 25,
		marginLeft: 20,
		marginRight: 20,
		borderBottomColor: '#e9e9e9',
		borderBottomWidth: 1,
	},
	tabsItem: {
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center',
		paddingLeft: 15,
		paddingRight: 15,
	},
	line: {
		width: 16,
		height: 3,
		marginTop: 3,
	},
	newsItem: {
		marginLeft: 20,
		marginRight: 20,
		paddingTop: 15,
		paddingBottom: 15,
		borderBottomColor: '#e9e9e9',
		borderBottomWidth: 1,
	},
	user: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	userText: {
		fontSize: 16
	},
	newsTitle: {
		fontSize: 18,
		lineHeight: 22,
		paddingBottom: 10,
		paddingTop: 10,
	},
	imgs: {
		flexDirection: 'row',

		alignItems: 'center',
	},
	imgsItem: {
		width: (Common.screenWidth - 70) / 3,
		height: (Common.screenWidth - 70) / 3,
		marginLeft: 5,
		marginRight: 5
	},
	hudong: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		paddingTop: 10,
	},
	hodongItem: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		marginLeft: 15,
	},
	addImg: {
		position: 'absolute',
		right: 30,
		bottom: 90,
	},
	fabuanniu: {
		width: 53,
		height: 53,
	},
	ceng: {
		width: Common.screenWidth,
		height: Common.screenHeight,
		position: 'absolute',
		left: 0,
		bottom: 0,
		zIndex: 9999999,
	},
	black: {
		height: Common.screenHeight - 185,
		backgroundColor: 'rgba(0,0,0,0.7)',
	},
	forbtn: {
		height: 166,
		paddingTop: 19,
		backgroundColor: '#fff',
	},
	close: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		width: Common.screenWidth,
		position: 'absolute',
		bottom: 10,
		left: 10,
	},

});
